/*******************************************************************************
*  Project      : Minigate Golfin                                 
*  Program ID   : pop_certify.js
*  Description  : 실명인증 
*
********************************************************************************
*  Program History                                                            
*  Date        Author    Description                                          
*  ----------  --------  -------------------------------------------------------- 
*  2012-05-08  김효순    Created.  
*  2012-05-08  김효순    Complete.  
*******************************************************************************/

jQuery(function($){
	// 입력폼
	function clsPhone()
	{
		this._HTMLDom = null;
		this._ERRMSG = {
			"NOVALUE": "핸드폰 번호가 모두 비었습니다."
			, "INVALID": "숫자만 입력 가능합니다."
		}
		this.errMsg = null;
		this.$errObj = null;
		
		this._init();
	}
	
	clsPhone.prototype = {
		_init: function(){
			var $layer = $("div.pw_area dl.pop_sms ol");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			$layer.find("input:text").attr("maxlength", 4);
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, valid: function(){
			var $layer = this.$getLayer();
			var thisClass = this;
			
			this.errMsg = null;
			this.$errObj = null;
			
			for(var i=0;i<$layer.find("li").length;i++){
				if(!($layer.find("li").eq(i).find("input:text:eq(0)").val() == "" || $layer.find("li").eq(i).find("input:text:eq(1)").val() == "")) break;
			}
			
			if(i >= $layer.find("li").length){
				this.errMsg = "NOVALUE";
				return false;
			}
			
			for(var i=0;i<$layer.find("input:text").length;i++){
				if($layer.find("input:text").eq(i).val() == "") continue;
				
				if(/\D/.test($layer.find("input:text").eq(i).val())) break;
			}
			
			if(i < $layer.find("input:text").length){
				this.errMsg = "INVALID";
				this.$errObj = $layer.find("input:text").eq(i);
				return false;
			}
			
			return true;
		}
		, getError: function(){
			if(!this.errMsg) return null;
			else return this._ERRMSG[this.errMsg];
		}
		, focus: function(){
			if(this.$errObj) this.$errObj.trigger("focus");
			else this.$getLayer().find("input:text:first").trigger("focus");
		}
		, getValue: function(){
			var szRet = "";
			var $layer = this.$getLayer();
			
			for(var i=0;i<$layer.find("li").length;i++){
				if(!($layer.find("li").eq(i).find("input:text:eq(0)").val() == "" || $layer.find("li").eq(i).find("input:text:eq(1)").val() == "")){
					if(szRet) szRet += ";";
					szRet += $layer.find("li").eq(i).find("option:selected").text() + "-" + $layer.find("li").eq(i).find("input:text:eq(0)").val() + "-" + $layer.find("li").eq(i).find("input:text:eq(1)").val();
				}
			}
			
			return szRet;
		}
	}
	
	function clsReserveInfo()
	{
		this._HTMLDom = null;
		this.infoData = null;
		
		this._init();
	}
	
	clsReserveInfo.prototype = {
		_init: function(){
			var $layer = $("div.sms_right");
			this._HTMLDom = {
				"$layer": $layer
			}
			
			this.setInfo({});
		}
		, $getLayer: function(){
			return this._HTMLDom["$layer"];
		}
		, setInfo: function(thisData){
			this.infoData = thisData;
			this.display()
		}
		, display: function(){
			var $layer = this.$getLayer();
			
			var mi = _gf.getMyInfoData();
			
			if(mi)	 $layer.find("dd").html("[골프인]부킹예약자 " + mi["이름"] + " 님의 부킹 동반 알림> " + this.infoData["날짜"] + "(" + this.infoData["요일"] + ") " + this.infoData["시간"] + " / " + this.infoData["골프장명"] + " " + this.infoData["코스명"] + " / " + this.infoData["홀명"]);
		}
		, getMessage: function(){
			return this.$getLayer().find("dd").text();
		}
	}
	
	function clsComm()
	{
		
		this._init();
	}
	
	clsComm.prototype = {
		_init: function(){

		}
		// 예약정보
		, getReserveInfo: function(arg){
			var thisClass = this;
			
			arg = arg || {}
			arg["콜백"] = arg["콜백"] || function(){}
			
			//ajax
			var serviceName = "getReservView";
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, {
				"reserv_seq": arg["예약코드"]
			}, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
					, "결과값": {
						"예약정보": {}
						, "코스정보": {}
					}
				}
				
				var items = ret["msp"]["contents"]["items"];
				if(items){
					var obj = items;
					
					var reserv_date = _util.nvl(obj["reserv__date"])+"";
					var reserv_time = _util.nvl(obj["reserv__time"])+"";
					var szEvent = "";
					var pDate = new Date(reserv_date.substr(0, 4), reserv_date.substr(4, 2)-1, reserv_date.substr(6, 2));
					pDate.setDate(pDate.getDate()-5);
					
					var e = [];
										
					if(obj["greenfee__use__yn"] == "Y"){
						szEvent = "그린피";
						e.push("그린피 할인: " + obj["greenfee__discount__amount"] +  _util.nvl(obj["greenfee_amt_type"]));
					}
					
//					if(obj["mileage__use__yn"] == "Y"){
//						e.push("마일리지: " + obj["mileage__amount"] +  obj["mileage__type"]);
//					}
					
					if(obj["cartfee__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "카트피";
						e.push("카트피: " + obj["cartfee__discount__amount"]);
					}
					
					if(obj["food__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "식사";
						e.push("식사: " + obj["food__discount__amount"]);
					}
					
					if(obj["present__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "선물";
						e.push("선물: " + obj["present__content"]);
					}
					
					if(obj["etc__use__yn"] == "Y"){
						if(szEvent) szEvent += ",";
						szEvent += "기타";
						e.push("기타: " + obj["etc__content"]);
					}
					
					res["결과값"]["예약정보"] = {
						"예약코드": arg["예약코드"]
						, "코스코드": "001"
						, "골프장명": _util.nvl(obj["golfclub__name"])
						, "코스명": _util.nvl(obj["course__info__name1"])
						, "홀명": _util.nvl(obj["hole"]) + "H"
						, "날짜": reserv_date.substr(0, 4) + "년 " + reserv_date.substr(4, 2) + "월 " + reserv_date.substr(6, 2) + "일"
						, "요일": _util.nvl(obj["reserv__day"])
						, "시간": reserv_time.substr(0, 2) + ":" + reserv_time.substr(2, 2)
						, "원가": _util.nvl(obj["price"], 0)
						, "가격": _util.nvl(obj["greenfee"], _util.nvl(obj["price"], 0))
						, "이벤트": szEvent
						, "보증결제금액": _util.nvl(obj["price__pay"], 0)
						, "예약상태": obj["reserv__status"]
						, "결제등급": obj["reserv__paytype"]
						, "가승인결제마감일": pDate
						, "이벤트리스트": e
					}
					
					res["결과값"]["코스정보"] = {
						"코스알림": _util.nvl(obj["course__notice"])
						, "코스명": _util.nvl(obj["course__info__name1"]) + ((obj["course__info__name2"]) ? ", " +obj["course__info__name2"]:"")
						, "상세정보": _util.nvl(obj["description"])
					}
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}
		, smsSubmit: function(arg){
			var thisClass = this;
			
			arg = arg || {};
			arg["콜백"] = arg["콜백"] || function(){}
			
			// ajax
			var serviceName = "reservAccessSMS";
			var options = {
				"reserv_seq": arg["예약코드"]
				, "sms_contents": arg["메시지"]
				, "to_phone": arg["휴대폰"]
			}
			_gf.ajax({
				"sid": "RS001"
				, "servicename": serviceName
			}, options, function(ret){
				var res = {
					"결과코드": ret["msp"]["contents"]["serviceResult"]
					, "메시지": document.objGlobal.getResultMsg(ret)
				}
				
				arg["콜백"].apply(null, [res]);
			});
		}

	}
	
	
	// 컨트롤
	function clsControl()
	{
		this.objComm = null;
		this.objPhone = null;
		this.objReserveInfo = null;
		
		this._permitStart = null;
		this.q_reserve = null;
		this.openerControl = null;
		
		this._init();
	}
	
	clsControl.prototype = {
		_init: function(){
			this._preload();
			
			this.objComm = new clsComm();
			this.objPhone = new clsPhone();
			this.objReserveInfo = new clsReserveInfo();
			
			this._bind();
			this._beforeStart();
			
			_util.setWindowSize();
		}
		, _preload: function(){
			_gf.spinStart();
			
			this.q_reserve = _util.getParam("q_reserve");
			
			if(opener && opener.document && opener.document.objControl) this.openerControl = opener.document.objControl;
		}
		, _bind: function(){
			var thisClass = this;
			
			$(document).on("click", "img[alt='sms보내기'], img[alt='취소'], img[alt='close']", function(){
				var alt = $(this).attr("alt");
				switch(alt){
					case "sms보내기":
						if(!thisClass.objPhone.valid()){
							alert(thisClass.objPhone.getError());
							thisClass.objPhone.focus();
							return;
						}
						
						thisClass.smsSubmit();
						break;
					case "취소":
					case "close":
						self.close();
				}
			});
		}
		, _beforeStart: function(){
			var thisClass = this;
			this._permitStart = {
				
			}
			
			if(!this.openerControl || !this.q_reserve){
				alert("비 정상적인 접근입니다.");
				self.close();
				$("body").remove();
				return;
			}
			
			_util.executeThread(function(){
				for(var k in thisClass._permitStart){
					if(!thisClass._permitStart[k]) return false;
				}
				
				return _gf.getMyInfoData();
			}, function(){
				_gf.spinEnd();
				thisClass._start();
			});
		}
		, _start: function(){
			var thisClass = this;
			
			_gf.spinStart();
			this.objComm.getReserveInfo({
				"예약코드": this.q_reserve
				, "콜백": function(ret){
					thisClass.finishReserveInfo(ret);
				}
			});
		}
		// 예약정보 완료
		, finishReserveInfo: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
				
			_gf.spinEnd();
			this.objReserveInfo.setInfo(ret["결과값"]["예약정보"]);
		}
		// 발송완료
		, finishSmsSubmit: function(ret){
			if(ret["메시지"]) alert(ret["메시지"]);
			if(ret["결과코드"] != "00000") return;
			
			_gf.spinEnd();
			self.close();
		}
		// sms발송
		, smsSubmit: function(){
			var thisClass = this;
			
			_gf.spinStart("sending...");
			thisClass.objComm.smsSubmit({
				"예약코드": this.q_reserve
				, "휴대폰": this.objPhone.getValue()
				, "메시지": this.objReserveInfo.getMessage()
				, "콜백": function(ret){
					thisClass.finishSmsSubmit(ret);
				}
			});
		}
	}
	
	document.objControl = new clsControl();
});